package com.example.sherlockzhong.plush_v2;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sherlockzhong.plush_v2.Components.buttons.BackButton;
import com.example.sherlockzhong.plush_v2.Models.DataModel;
import com.example.sherlockzhong.plush_v2.View.CollectionHorizontalScrollView;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;


public class CollectionActivity extends Activity {

    public JSONArray collectedData = null;
    private CollectionActivity self = this;
    private boolean isDeleting = false;
    private boolean deleteFinished = true;
    private ImageView deleteButton = null;
    private ArrayList deleteIcons = new ArrayList();

    private CollectionHorizontalScrollView collectionScroller = null;
    private LinearLayout collectionContainer = null;

    private Handler removeHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collection);

        BackButton collection_back = (BackButton) findViewById(R.id.collection_back);
        collection_back.setApp(this);

        collectedData = DataModel.retrieveCollectedData();
        if (collectedData != null && collectedData.length() > 0) {
            generateCollectedData();
            deleteButton = (ImageView) findViewById(R.id.collection_delete);
            deleteButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showDeletButton();
                }
            });
        } else {
            Toast.makeText(this.getBaseContext(), "暂时没有收藏的卡片哦", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    private void generateCollectedData() {
        collectionScroller = (CollectionHorizontalScrollView) findViewById(R.id.collection_scroller);

        Display display = getWindowManager().getDefaultDisplay();
        final int windowWidth = display.getWidth();
        int windowHeight = display.getWidth();

        collectionScroller.setParams(collectedData.length(), windowWidth, windowHeight);

        collectionContainer = (LinearLayout) findViewById(R.id.collection_container);
        try {
            for (int i = 0; i < collectedData.length(); i++) {
                View collectedItem = getLayoutInflater().inflate(R.layout.collected_item, collectionContainer, false);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(windowWidth - 20 * 2, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
                params.setMargins(20, 20, 20, 20);
                collectedItem.setLayoutParams(params);
                collectionContainer.addView(collectedItem, 0);

                JSONObject data = (JSONObject) collectedData.get(i);

                ImageView deleteIcon = (ImageView) collectedItem.findViewById(R.id.collected_item_delete);
                deleteIcon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        removeCollectedItem(view);
                    }
                });
                deleteIcons.add(deleteIcon);

                ImageView icon = (ImageView) collectedItem.findViewById(R.id.collected_item_icon);
                if (data.getString("card_type").equalsIgnoreCase("organization")) {
                    icon.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.love));
                } else if (data.getString("card_type").equalsIgnoreCase("tutor")) {
                    icon.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.teacher));
                } else if (data.getString("card_type").equalsIgnoreCase("myclass")) {
                    icon.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.classmate));
                } else if (data.getString("card_type").equalsIgnoreCase("official")) {
                    icon.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.logo));
                }

                TextView author = (TextView) collectedItem.findViewById(R.id.collected_item_author);
                TextView time = (TextView) collectedItem.findViewById(R.id.collected_item_time);
                TextView title = (TextView) collectedItem.findViewById(R.id.collected_item_title);
                TextView place = (TextView) collectedItem.findViewById(R.id.collected_item_place);
                TextView timespan = (TextView) collectedItem.findViewById(R.id.collected_item_timespan);
                TextView content = (TextView) collectedItem.findViewById(R.id.collected_item_content);

                author.setText(data.getString("name"));
                time.setText(data.getString("create_time"));
                title.setText(data.getString("title"));
                content.setText(data.getString("content"));
                // content.setMinHeight(windowHeight - DisplayUtil.dip2px(this.getBaseContext(), 20));

                if (data.getString("card_type").equalsIgnoreCase("organization")) {
                    place.setText(data.getString("place"));
                    timespan.setText(data.getString("start_time") + " ~ " + data.getString("end_time"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showDeletButton() {
        if (isDeleting) {
            deleteButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.delete));
            isDeleting = false;
            for (int i = 0; i < deleteIcons.size(); i++) {
                ImageView deleteIcon = (ImageView) deleteIcons.get(i);
                deleteIcon.setVisibility(View.INVISIBLE);
            }
        } else {
            deleteButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.deleting));
            isDeleting = true;
            for (int i = 0; i < deleteIcons.size(); i++) {
                ImageView deleteIcon = (ImageView) deleteIcons.get(i);
                deleteIcon.setVisibility(View.VISIBLE);
            }
        }
    }

    private void removeCollectedItem(View view) {
        if (isDeleting && deleteFinished) {
            deleteFinished = false;
            final int index = deleteIcons.indexOf((ImageView) view);
            Animation shrink = AnimationUtils.loadAnimation(self.getBaseContext(), R.anim.shrink);
            collectionContainer.getChildAt(collectedData.length() - 1 - index).startAnimation(shrink);
            removeHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    collectionContainer.removeViewAt(collectedData.length() - 1 - index);
                    deleteIcons.remove(index);
                    removeCollectedData(index);
                    collectionScroller.setParams(collectedData.length(), collectionScroller.windowWidth, collectionScroller.windowHeight);
                    collectionScroller.childrenLength--;
                    if (collectedData.length() <= 0) {
                        deleteButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.delete));
                        Toast.makeText(self.getBaseContext(), "已经没有收藏的卡片了", Toast.LENGTH_SHORT).show();
                    }
                    deleteFinished = true;
                }
            }, 300);
        }
    }

    private void removeCollectedData(int index) {
        try {
            JSONArray newAllData = new JSONArray();
            for (int i = 0; i < collectedData.length(); i++) {
                if (i != index) {
                    newAllData.put(collectedData.get(i));
                }
            }
            collectedData = newAllData;
            DataModel.saveCollectedData(collectedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
